package com.ac.scum.log.web.model.wechat.mp.handler.msg.stage;

import com.ac.scum.wechat.bean.WechatMpKeyword;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
public class KeywordMsgStage {

    private final RedisTemplate<String, Object> redisTemplate;

    public String getKeywordReply(String context) {
        String key = "wechat::mp::keyword";
        List<WechatMpKeyword> wechatMpKeywords = Objects.requireNonNull(redisTemplate.opsForList().range(key, 0, -1))
                .stream()
                .map(item -> (WechatMpKeyword) item)
                .filter(item -> item.getKeyword().equals(context))
                .toList();
        if (wechatMpKeywords.isEmpty()) {
            return null;
        }
        if (wechatMpKeywords.size() == 1) {
            return wechatMpKeywords.get(0).getContext();
        } else {
            List<WechatMpKeyword> list = wechatMpKeywords.stream().filter(item -> !item.getPrivateFlag()).toList();
            if (!list.isEmpty()) {
                //公共回复
                return list.get(0).getContext();
            }

            // TODO 后续 查询该用户绑定了那个服务器 并且回复该服务器定制化关键词回复。 如果没绑定则返回空，或者非定制化内容
            return null;
        }
    }
}
